#/*************************************************************************
#    > File Name: Yaml_Operation.py
#    > Author: Yan Wang
#    > Mail: wangyan@imnu.edu.cn
#    > Created Time: Fri 03 Jun 2022 03:30:42 PM CST
# ************************************************************************/
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import yaml
from List_Operation import *

# 读取yaml文件
def Read_Yaml(file_name):   
	with open(file_name,"r") as stream:   #只读模式打开file_name
		data_loaded = yaml.safe_load(stream)   #传入SafeLoader的解析器，解析基本的yaml标记，用来保证代码的安全性。
	return(data_loaded)

# 读取yaml文件, 并显示所有关键词:
def Show_Keys_in_Yaml(file_name):
	data_loaded=Read_Yaml(file_name)
	keys=data_loaded.keys()
	return(keys)

# 读取yaml文件, 并找到关键词对应的数据:
def Locate_Key_in_Yaml(file_name,key):
	data_loaded=Read_Yaml(file_name)
	keys=data_loaded.keys()
	key_exist=Judge_Element_Exist(keys,key)
	if key_exist is False:
		print("no such key in {}".format(file_name))
		return(False)
	else:
		return(data_loaded[key])


# 下面会用到的函数， 为了让yaml的输出可以对齐，且没有额外的引号
def dict_representer(dumper, data):
	keyWidth = max(len(k)+5 for k in data)
	aligned = {k+' '*(keyWidth-len(k)):v for k,v in data.items()}
	return dumper.represent_mapping('tag:yaml.org,2002:map', aligned)
			

def quoted_presenter(dumper, data):
	return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')


yaml.add_representer(dict, dict_representer)
yaml.add_representer(str, quoted_presenter)


# 将yaml文件复制为一个新文件，且修改某一个key值，
def Modify_Value(file_name,key,value):
	data_loaded=Read_Yaml(file_name)
	data_loaded[key]=value
	with open(file_name,"w") as stream:   #“w”只写模式
		yaml.dump(data_loaded, stream, default_flow_style=False, sort_keys=False, width=100, indent=20)


# 将yaml文件复制为一个新文件，且修改某一个key值，
def Modify_Value_R(file_name,key,value):
	string=open(file_name,"r") 
	data_loaded=yaml.safe_load(string)
	data_loaded[key]=value
	stream=yaml.dump(data_loaded, default_flow_style=False, sort_keys=False, width=100, indent=20)
	string=open(file_name,"w") 
	string.write(stream.replace("\'",""))
	#data_loaded[key]=value
	#yaml.dump(data_loaded, stream)


